package com.example.mspay.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Service
@RequiredArgsConstructor
public class AlipayService {
    @Autowired
    private  AlipayClient alipayClient;

    /**
     * 电脑网站支付
     */
    public String createOrder(String orderNo, BigDecimal amount, String subject) throws AlipayApiException {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl("http://localhost:3000/OrderView");
        request.setNotifyUrl("http://x66fd998.natappfree.cc/alipay/notify");

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        bizContent.put("total_amount", amount.setScale(2, RoundingMode.HALF_UP));
        bizContent.put("subject", subject);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        JSONArray goodsDetails = new JSONArray();
        JSONObject goodsDetail = new JSONObject();
        goodsDetail.put("goods_id", "GOODS_" + orderNo);
        goodsDetail.put("goods_name", subject);  // 正确的参数名
        goodsDetail.put("quantity", 1);
        goodsDetail.put("price", amount.setScale(2, RoundingMode.HALF_UP));
        goodsDetails.add(goodsDetail);
        bizContent.put("goods_detail", goodsDetails);  // 正确的参数名
        request.setBizContent(bizContent.toJSONString());
        return alipayClient.pageExecute(request).getBody(); // 返回支付页面HTML
    }

    /**
     * 查询订单状态
     */
    public String queryOrder(String orderNo) throws AlipayApiException {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{\"out_trade_no\":\"" + orderNo + "\"}");
        return alipayClient.execute(request).getBody();
    }


}